//
//  ServiceModelManager.swift
//  home
//
//  Created by Yun Zeng on 2019/1/31.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import Foundation

extension HMServiceType {
    static func getCustomService(service: Service) -> ServiceCellDelegate {
        var custom: ServiceCellDelegate?
        guard let sevType = HMServiceType(rawValue: service.type) else {
            return ServiceDefault(service: service)!
        }
        
        switch sevType {
        case .clock:
            custom = ServiceMusicClock(service: service)
        case .contactSensor:
            custom = ServiceSensorContact(service: service)
        case .htSensor:
            custom = ServiceHTSensor(service: service)
        case .colorLight:
            custom = ServiceLightHue(service: service)
        case .zigbeeCoordinator:
            custom = ServiceCoordinator(service: service)
        case .motion:
            custom = ServiceSensorMotion(service: service)
        case .airConditioner:
            custom = ServiceAirConditioner(service: service)
        case .button:
            custom = ServiceSceneButton(service: service)
        case .outlet:
            custom = ServiceOutlet(service: service)
        case .temperatureColorLight:
            custom = ServiceLightColorTemperature(service: service)
            
        default:
            custom =  ServiceDefault(service: service)
        }
        return custom ?? ServiceDefault(service: service)!
    }
}

// 服务显示模型管理
class ServiceModelManager: ServiceUpdateObserver {
    internal let identify = "adai.design.home.custom.service.manager"
    // 服务管理
    private var manager: ServiceManager!
    
    // 定制显示内容
    open var customs = [ServiceCellDelegate]()

    init(manager: ServiceManager) {
        self.manager = manager
        for service in self.manager.services {
            let custom = HMServiceType.getCustomService(service: service)
            self.customs.append(custom)
        }
        self.manager.addObserver(identify: self.identify, observer: self)
    }
    
    var onUpdate: ((Int)->Void)?
    func update(services: Set<Service>) {
        for (index, custom) in self.customs.enumerated() {
            if services.contains(custom.service) {
                self.onUpdate?(index)
            }
        }
    }
    
    // 点击事件
    func toggleAtIndex(index: Int) -> Bool {
        let custom = self.customs[index]
        if let action = custom.toggle() {
            Logger.Info("action: \(action.description)")
            _ = self.manager.executeActions(actions: action)
            self.onUpdate?(index)
            return true
        }
        return false
    }
    
}
